var express = require('express');
var router = express.Router();
var mgdb = require('../../../utils/mgdb');
const mongodb = require('mongodb');
let ObjectId = mongodb.ObjectId;

/* GET home page. */
router.delete('/', function (req, res, next) {
    // cart清空购物车
    let { cartid, goodsid } = req.body
    if (!cartid) {
        res.send({ err: 1, msg: '购物车id为必传参数' })
        return;
    }
    goodsid = goodsid ? JSON.parse(goodsid) : []
    req.mgdb.open({ collectionName: 'cart' }).then(({ collection, client }) => {
        if (goodsid[0]) {
            collection.find({ _id: ObjectId(cartid) }, { projection: { _id: 0, username: 0 } }).toArray((err, result) => {
                if (err) {
                    res.send({ err: 1, msg: "操作集合失败" })
                } else {
                    if (result.length > 0) {
                        for (let i = 0; i < goodsid.length; i++) {
                            let index = null;
                            let flag = null
                            // 遍历用户购物车里的商品，判断商品索引
                            flag = result[0].goods.some((val, idx) => {
                                index = idx;
                                return val.proid === goodsid[i];
                            })
                            if (flag) {
                                result[0].goods.splice(index, 1);
                            }
                        }
                        let goods = result[0].goods;
                        collection.updateOne({ _id: cartid }, { $set: { goods } }, { upsert: false, projection: false }, (err, result) => {
                            if (err) {
                                res.send({ err: 1, msg: '操作集合失败' });
                            } else {
                                res.send({ err: 0, msg: '删除成功', data: result.result })
                            }
                            client.close();
                        })
                    } else {
                        res.send({ err: 1, msg: "查无数据" })
                    }

                }
            })
        } else {
            let goods = []
            collection.updateOne({ _id: cartid }, { $set: { goods } }, { upsert: false, projection: false }, (err, result) => {
                if (err) {
                    res.send({ err: 1, msg: '操作集合失败' });
                } else {
                    res.send({ err: 0, msg: '清除购物车成功', data: result.result })
                }
                client.close();
            })
        }
    }).catch(
        e => res.send(e)
    )
})
module.exports = router;